package com.sims.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 1L;
	// 需要定义系统页面访问中可放行的连接
	private List<String> list = new ArrayList<String>();

	public void init(FilterConfig arg0) throws ServletException {
		// 定义不被拦截的页面
		list.add("/login.jsp");
		list.add("/login!login.action");
		// 注册
		list.add("/registeaccount.jsp");
		list.add("/login!registeAccount.action");
	}

	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
			FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;
		// 获取页面中的访问的路径连接
		String url = request.getServletPath();
		if (url.equals("")) {
			url += "/";
		}
		// 从session对象中获取当前登录的用户
		String user = (String) request.getSession().getAttribute("currentUserAccount");
		// 如果有排除界面或者session对象中获取到了当前登录的用户，则放行
		// 否则提示未登录，调整到登录页面进行登录
		if (list.contains(url) || user != null) {
			filterChain.doFilter(request, response);
			return;
		} else {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.println("<script>alert('未登录,请先登录。');window.location.href='login.jsp';</script>");
			out.flush();
			out.close();
			//response.sendRedirect( request.getContextPath() + "/login.jsp");
			return;
		}
	}
}